<?php

namespace App\Observers;

use App\Models\Message;
use App\Models\Order;
use App\Models\Shop;
use App\Models\User;
use App\Models\UserData;
use App\Models\Wallet;
use Illuminate\Support\Facades\DB;

class UserObserver
{
    /**
     * 监听创建用户前事件.
     *
     * @param User $model
     * @return void
     */
    public function creating(User $model)
    {
        $model->user_nu = user_nu();
        $model->login_status = User::NORMAL;
        $model->gag_status = User::NORMAL;
    }

    /**
     * 监听创建用户事件.
     *
     * @param User $model
     * @return void
     */
    public function created(User $model)
    {
        $model->wallet->push();

        Message::create([
            'user_id' => $model->id,
            'title' => trans('api.register_succeed'),
            'content' => trans('api.register_message'),
        ]);

    }

    public function updated(User $model)
    {
        if ($model->isDirty('avatar')) {
            $model->shop->face_picture = $model->avatar;

            $model->push();
        }
    }

    /**
     * 监听删除用户事件.
     *
     * @param User $model
     * @return void
     */
    public function deleting(User $model)
    {
        //
    }

    /**
     * 监听删除用户事件.
     *
     * @param User $model
     * @return void
     */
    public function deleted(User $model)
    {
        DB::transaction(function () use ($model) {
            $wallet = new Wallet();
            $wallet->where('user_id', $model->id)->delete();

            $data = new UserData();
            $data->where('user_id', $model->id)->delete();

            if ($model->role == User::SELLER) {
                $shop = new Shop();
                $shop->where('user_id', $model->id)->delete();
            }
        });
    }
}
